import logging, os
from logging.handlers import RotatingFileHandler

# 按文件大小滚动的日志
#创建logs文件夹
if not os.path.exists('./data/logs'):
    os.mkdir('./data/logs')
# 创建一个logger
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)  # 设置日志级别为DEBUG
logger.propagate = False # 阻止日志向上传递

# 创建一个RotatingFileHandler，设置最大日志文件大小为1MB，最多保留50个备份文件
handler = RotatingFileHandler('./data/logs/main.log', maxBytes=1 * 1024 * 1024, backupCount=50, encoding='utf-8')
handler.setLevel(logging.INFO)
# 创建一个控制台handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)

# 设置日志格式
formatter = logging.Formatter('[%(asctime)s][%(levelname)s] - %(message)s')
handler.setFormatter(formatter)
console_handler.setFormatter(formatter)

# 将handler添加到logger
logger.addHandler(handler)
logger.addHandler(console_handler)
